/***********************************************************************
 * 分布表单设计
 * *********************************************************************/

import {
    NForm, NGrid, NGi, NSteps, NStep, NButton, NCard, NFormItem, NInput,
    NSelect,
    NDatePicker,
    NRadioGroup,
    NCheckboxGroup,
    NSpace,
    NRadio,
    NCheckbox,
    NSwitch,
    NCascader
} from "naive-ui";
import { DefineComponent, defineComponent, ref, } from "vue";


type MySize = 'tiny' | 'small' | 'medium' | 'large' | undefined;
type Mypassword = "textarea" | "text" | "password" | undefined;

export interface flexformitem {
    slot?: string,
    show: boolean,   // 是否显示
    span: string,  //  宽度
    label: string, // 标题
    key: string, // 关键字
    default: string, // 默认值
    type: string, // 表单类型
    placeholder?: string,// 提示文字
    inputtype?: string, // input输入框的类型
    clearable?: boolean, // 清楚按钮
    disabled?: boolean,// 不可编辑
    size: MySize, // 大小
    change?: null | Function,  // 改变的回调
    options?: Array<any>, // 备选项
    required: string, // 是否必填
    maxlength?: string, // 最大长度
    multiple?: string,  // 是否多选
    tooltip?: string, // 滑块覆盖的提示
    placement?: string, // 提示的弹出位置
    max?: string, // 最大值
    min?: string, // 最小值
    datatype?: string, // 时间选择器的类型
    round?: string,  // 是否是圆形
    valueField?: string,   // 关键字
    labelField?: string, // 关键字
    childrenField?: string,  // 关键字
    filterable?: string,  // 过滤功能
    rules?: Array<any> | undefined,  // 校验规则
    path: string | undefined,   // 所在路径
    password: Mypassword,    // 是不是密码
    prefix: Function | undefined, //前缀
    suffix: Function | undefined,   //后缀
}


type MyFunction = (e: KeyboardEvent) => {}
// 回车按下的无效化
export const meiyongfunc = (event: KeyboardEvent) => {
    if (event.key === "Enter") {
        event.preventDefault()
    }
}

export default defineComponent({
    name: "manystepForm",
    props: {
        value: {
            default(data: any) {
                return data
            },
        },
        labelWidth: {
            type: Number,
            default: 100,
        },
        formList: {
            default(data: Array<flexformitem>) {
                return data
            },
        },
        handleClose: {
            type: Function,
        },
    },
    setup({ value, labelWidth, handleClose, }, { emit, expose }) {
        // 步骤条的组件
        const stepsRef = ref(null)
        // 临时用的表单配置
        const formList = [
            {
                title: "第一步", form: [
                    {
                        span: 24,
                        label: "字典名称1",
                        key: "name1",
                        default: "",
                        type: "input",
                        placeholder: "请输入名称",
                        rules:[
                            {required:true,message:"请输入名称",trigger:"change"}
                        ],
                    },
                    {
                        span: 24,
                        label: "描述1",
                        key: "desc4",
                        default: "",
                        type: "textarea",
                        placeholder: "请输入描述",
                        rules:[
                            {required:true,message:"请输入描述",trigger:"change"}
                        ],
                    },
                ]
            },
            {
                title: "第二步", form: [
                    {
                        span: 24,
                        label: "字典名称2",
                        key: "name2",
                        default: "",
                        type: "input",
                        placeholder: "请输入名称",
                        rules:[
                            {required:true,message:"请输入名称",trigger:"change"}
                        ],
                    },
                    {
                        span: 24,
                        label: "描述2",
                        key: "desc3",
                        default: "",
                        type: "textarea",
                        placeholder: "请输入描述",
                        rules:[
                            {required:true,message:"请输入描述",trigger:"change"}
                        ],
                    },
                ]
            },
            {
                title: "第三步", form: [
                    {
                        span: 24,
                        label: "字典名称3",
                        key: "name3",
                        default: "",
                        type: "input",
                        placeholder: "请输入名称",
                        rules:[
                            {required:true,message:"请输入名称",trigger:"change"}
                        ],
                    },
                    {
                        span: 24,
                        label: "描述3",
                        key: "desc2",
                        default: "",
                        type: "textarea",
                        placeholder: "请输入描述",
                        rules:[
                            {required:true,message:"请输入描述",trigger:"change"}
                        ],
                    },
                ]
            },
            {
                title: "第四步", form: [
                    {
                        span: 24,
                        label: "字典名称4",
                        key: "name",
                        default: "",
                        type: "input",
                        placeholder: "请输入名称",
                        rules:[
                            {required:true,message:"请输入名称",trigger:"change"}
                        ],
                    },
                    {
                        span: 24,
                        label: "描述4",
                        key: "desc1",
                        default: "",
                        type: "textarea",
                        placeholder: "请输入描述",
                        rules:[
                            {required:true,message:"请输入描述",trigger:"change"}
                        ],
                    },
                ]
            },

        ]
        const formRef = ref<null | DefineComponent>(null)
        const rules = ref({})
        const current = ref(1)
        const currentStatus = ref<"wait" | "error" | "finish" | "process" | undefined>("process")
        const handleNext = (index: number) => {
            if (index === 1) {
                formRef.value?.validate((errors: any) => {
                    if (!errors) {
                        // 如果是下一步，必须是当前页面没有报错才可以
                        current.value = current.value + index
                        if (current.value === 1) {
                            stepsRef.value!.$el!.scrollLeft = 0
                        } else if (current.value === formList.length) {
                            stepsRef.value!.$el!.scrollLeft = 10000
                        } else {
                            stepsRef.value!.$el!.scrollLeft = current.value / formList.length * stepsRef.value?.$el?.clientWidth || 0
                        }
                    } else {
                        return false
                    }
                })
            } else {
                // 上一步不需要验证
                current.value = current.value + index
                if (current.value === 1) {
                    stepsRef.value!.$el!.scrollLeft = 0
                } else if (current.value === formList.length) {
                    stepsRef.value!.$el!.scrollLeft = 10000
                } else {
                    stepsRef.value!.$el!.scrollLeft = current.value / formList.length * stepsRef.value?.$el?.clientWidth || 0
                }
            }
        }
        // 刷新回显e
        const shuaxin = (key: string | null = null, data: any) => {
            // console.log("要修改的key是：", key,data,{...value})
            if (key) {
                value[key] = data
            }
            // console.log({...value}, "现在的数据")
            // emit("update:value", {...value})
            emit("change",)
        }
        // 点击保存
        const handleSave = () => {
            console.log("点击保存");
        }
        // 具体的输入组件
        const biaodanitem: { [key: string]: any } = {
            "slot": (item: any) => (item.slot ? item.slot(item, shuaxin) : null),
            "input": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NInput v-model={[value[item.key], "value"]} onKeydown={meiyongfunc}
                        type={item.password || "text"}
                        onUpdateValue={(val) => shuaxin(item.key, val)} placeholder={item.placeholder || "请输入"}
                        clearable={item.clearable} disabled={item.disabled}
                        size={item.size || "small"}>
                        {item.prefix ? item.prefix() : null}
                        {item.suffix ? item.suffix() : null}
                    </NInput>
                </NFormItem>),
            "textarea": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NInput v-model={[value[item.key], "value"]} onKeydown={meiyongfunc} type={"textarea"}
                        onUpdateValue={(val) => shuaxin(item.key, val)} placeholder={item.placeholder || "请输入"}
                        clearable={item.clearable} disabled={item.disabled}
                        size={item.size || "small"}>
                    </NInput>
                </NFormItem>),
            "select": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NSelect v-model={[value[item.key], "value"]}
                        onUpdateValue={(val) => shuaxin(item.key, val)} placeholder={item.placeholder || "请选择"}
                        clearable={item.clearable} disabled={item.disabled} options={item.options || []}
                        filterable={item.filterable} multiple={item.multiple} size={item.size || "small"}>
                    </NSelect>
                </NFormItem>),
            "picker": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NDatePicker v-model={[value[item.key], "value"]} type={item.dateType || "datetime"}
                        onUpdateValue={(val) => shuaxin(item.key, val)} placeholder={item.placeholder || "请选择"}
                        clearable={item.clearable} disabled={item.disabled} size={item.size || "small"}>
                    </NDatePicker>
                </NFormItem>),
            "radio": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NRadioGroup v-model={[value[item.key], "value"]}
                        onUpdateValue={(val) => shuaxin(item.key, val)}
                        disabled={item.disabled} size={item.size || "small"}>
                        <NSpace>
                            {() => item.options.map((option: any) => {
                                return <NRadio value={option.value}>{option.label}</NRadio>
                            })}
                        </NSpace>
                    </NRadioGroup>
                </NFormItem>),
            "checkbox": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NCheckboxGroup v-model={[value[item.key], "value"]}
                        onUpdateValue={(val) => shuaxin(item.key, val)}
                        disabled={item.disabled} size={item.size || "small"}>
                        <NSpace>
                            {item.options.map((option: any) => {
                                return () => (
                                    <NCheckbox value={option.value} label={option.label} />
                                )
                            })}
                        </NSpace>
                    </NCheckboxGroup>
                </NFormItem>),
            "switch": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NSwitch v-model={[value[item.key], "value"]}
                        onUpdateValue={(val) => shuaxin(item.key, val)} round={item.round}
                        disabled={item.disabled} size={item.size || "small"}>
                    </NSwitch>
                </NFormItem>),
            "cascader": (item: any) => (
                <NFormItem label={item.label + "："} path={item.path || item.key} rule={item.rules || []}>
                    <NCascader v-model={[value[item.key], "value"]}
                        onUpdateValue={(val) => shuaxin(item.key, val)} placeholder={item.placeholder || "请选择"}
                        options={item.options || []} showPath={item.showPath} clearable={item.clearable}
                        valueField={item.valueField || "id"} labelField={item.labelField || "name"}
                        disabled={item.disabled} size={item.size || "small"}>
                    </NCascader>
                </NFormItem>),
        }
        return () => (<NForm ref={formRef} model={value} rules={rules.value}
            label-width={labelWidth}
            label-placement="left">
            <NSpace class="px-4 py-2 overflow-x-auto overflow-y-hidden" ref={stepsRef}>
                <NSteps
                    size={"small"}
                    current={current.value}
                    status={currentStatus.value}
                >
                    {formList.map(item => {
                        return <NStep title={item.title}>
                        </NStep>
                    })}
                </NSteps>
            </NSpace>
            <NCard>
                <NGrid xGap={12}>
                    {formList[current.value - 1].form.map((item: any) => {
                        return <NGi span={item.span || 24} key={item.key}>
                            {biaodanitem[item.type] && item.show !== false ? biaodanitem[item.type](item) : null}
                        </NGi>
                    })}
                </NGrid>
            </NCard>
            <NSpace justify={"end"}>
                <NButton class="w-80px" onClick={() => handleClose()}>取消</NButton>
                {current.value !== 1 ? <NButton class="w-80px" type={"primary"} onClick={() => handleNext(-1)}>上一步</NButton> : <div class="w-80px"></div>}
                {current.value === formList.length ? <NButton type={"info"} class="w-80px" onClick={() => handleSave()}>保存</NButton> : <NButton type={"primary"} class="w-80px" onClick={() => handleNext(1)}>下一步</NButton>}
            </NSpace>
        </NForm >)
    },
})